
package saxon.gui.model.swing;

import saxon.gui.utils.Pair;
import saxon.gui.model.XModelImpl;
import java.io.File;
import java.util.List;
import javax.swing.SwingWorker;
import net.sf.saxon.s9api.XdmValue;
import saxon.gui.model.XWorker;

/**
 *
 * @author lennyn
 */
public class SwingXWorker extends SwingWorker<Void, Pair<File, XdmValue>> implements XWorker {

	private final XModelImpl model;
	private Exception exception;

	public SwingXWorker(XModelImpl model) {
		this.model = model;
	}

	@Override
	public void publishPartialResult(File file, XdmValue value) {
		this.publish(new Pair<File, XdmValue>(file, value));
	}

	@Override
	public void scheduleProcessing() {
		this.execute();
	}

	@Override
	protected Void doInBackground() {
		try {
			model.doProcessFiles();
		}
		catch (Exception ex) {
			this.exception = ex;
		}
		return null;
	}

	@Override
	protected void process(List<Pair<File, XdmValue>> values) {
		for (Pair<File, XdmValue> val: values)
			model.doPublishPartialResult(val.getFirst(), val.getSecond());
	}

	@Override
	protected void done() {
		if (exception == null)
			model.done();
		else
			model.error(exception.getLocalizedMessage());
	}
}
